package org.example.repeater.handler;

import com.github.benmanes.caffeine.cache.Cache;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.example.repeater.message.Constant.*;

public class ClientHandler  extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);
    private Cache<String, Object> caffeineCache;
    private String address;
    private ChannelHandlerContext deviceContext;
    public ClientHandler(String address, Cache<String, Object> caffeineCache) {
        this.caffeineCache=caffeineCache;
        this.address=address;

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        caffeineCache.put(clientPref+address, ctx);
        Object o =  caffeineCache.getIfPresent(clientHandlerPref+address);
        if (o==null){
            o=new Object();
            caffeineCache.put(clientHandlerPref+address,o);
        }
        synchronized (o){
            o.notify();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
            ByteBuf buf = (ByteBuf) msg;
            //获取设备channel
            if (deviceContext==null) {
                deviceContext=(ChannelHandlerContext)caffeineCache.getIfPresent(devicePref+address);
            }
            log.info("终端<<<<<<{}-[{}]",address, ByteBufUtil.hexDump(buf));
            deviceContext.writeAndFlush(buf);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("连接808网关出现异常,原因如下:{} ",cause.getCause().toString());
        cause.printStackTrace();
        release();
    }
    public void release() {
        if (address != null) {
            caffeineCache.invalidate(clientPref+address);
            caffeineCache.invalidate(dataPref+address);
            log.info("808网关断开连接 {}",address);
            address=null;
        }
    }

}
